<template>
  <div id="login_wap"  v-loading="loading"  element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
        <div  class="login-bg">
            <div class="login-box">
                <h2>欢迎光临</h2>
                <div class="login-content">
                    <div class="login-userName">
                      <el-form :model="loginForm" status-icon :rules="rules2" ref="loginForm" label-width="0" class="demo-ruleForm">
                          <div class="number_login" v-if="number_login == true">
                              <el-form-item >
                                    <el-input type="text" v-model="loginForm.identifier" auto-complete="off"  placeholder="请输入账号"></el-input>
                              </el-form-item>
                              <el-form-item prop="credential">
                                    <el-input type="password" v-model="loginForm.credential" auto-complete="off"  placeholder="密码"></el-input>
                              </el-form-item>
                          </div>
                          <div class="Phone_login" v-if="phonePassword_login == true">
                              <el-form-item>
                                    <el-input type="text" v-model="loginForm.user" auto-complete="off"  placeholder="请输入手机号"></el-input>
                              </el-form-item>
                              <el-form-item >
                                    <el-input type="password" v-model="loginForm.pass" auto-complete="off"  placeholder="密码"></el-input>
                              </el-form-item>
                          </div>
                          <div class="Phone_login" v-if="phoneCode_login == true">
                              <el-form-item>
                                    <el-input type="text" v-model="loginForm.mobile" placeholder="请输入手机号"></el-input>
                              </el-form-item>
                              <div class="code_box">
                                <!-- <el-form-item>
                                      <el-input type="text" v-model="loginForm.code" auto-complete="off"  placeholder="请输入验证码"></el-input>
                                      <el-button type="primary" class="code" @click="getCdoe()"  v-show="show">获取验证码</el-button>
                                      <el-button type="info" class="code" v-show="!show">{{count}}秒重新发送</el-button>
                                </el-form-item> -->
                                  <el-form-item>
                                    <div class="img_box">
                                        <el-input type="text" v-model="loginForm.sign" auto-complete="off"  placeholder="请输入图形验证码" class="codeImg"></el-input>
                                        <img :src="sign" alt="" style="height: 46px;margin-top: -7px;;cursor: pointer;" @click="cut">
                                    </div>
                                  </el-form-item>
                                  <el-form-item>
                                        <el-input type="text" v-model="loginForm.code" auto-complete="off"  placeholder="请输入验证码"></el-input>
                                        <el-button type="primary" class="code" @click="getCdoe()"  v-show="show">获取验证码</el-button>
                                        <el-button type="info" class="code" v-show="!show">{{count}}秒重新发送</el-button>
                                  </el-form-item>

                              </div>
                          </div>
                          <el-form-item>
                              <el-button type="primary" @click="handleLogin('loginData')" class="submit_btn">登陆</el-button>
                              <div class="password_box">
                                <p class="forget_password" v-if="phoneCode_login == false" @click="modeLogin(1)">手机验证登录</p>
                                <p class="forget_password" v-if="number_login == false" @click="modeLogin(2)">账号密码登录</p>
                                <p class="forget_password" v-if="phonePassword_login == false" @click="modeLogin(3)">手机密码登录</p>
                              </div>
                          </el-form-item>
                    </el-form>
                    </div>
                    <!-- <div class="login-password">

                    </div> -->
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { isvalidUsername } from '@/utils/validate'
import LangSelect from '@/components/LangSelect'
import SocialSign from './socialsignin'
// import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getNoteCode , login} from '@/api/login'
import { Base64 } from 'js-base64';
export default {
  name: 'Login',
  components: { LangSelect, SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        identifier: '',
        credential: '',
        mobile : '',
        sign : '',
        code :'',
        ticket :''
      },
      kid :'',

      rules2: {
        identifier: [
          { required: true, message : '请输入密码',trigger: 'blur' }
        ],
        credential: [
          { required: true, message : '请输入用户名',trigger: 'blur' }
        ],
        phoneCode_login: [
          { required: true, message : '请输入验证码',trigger: 'blur' }
        ],
        iphone :[
          { required: true, message : '请输入手机号',trigger: 'blur' }
        ],
      },
      passwordType: 'password',
      loading: false,
      showDialog: false,
      redirect: undefined,
      number_login : true,
      phoneCode_login : false,
      phonePassword_login : false,
      show: true,
      count: '',
      timer: null,
      data:{},
      sign :''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  },
  mounted(){
    window.onkeydown = (e)=>{
      if(e.keyCode==13){
        this.handleLogin()
      }
    }
  },
  methods: {
    modeLogin (index) {
      if (index == 3) {
        this.number_login = false;
        this.phonePassword_login = true;
        this.phoneCode_login = false
        this.loginForm.user = '';
        this.loginForm.pass = '';
      } else if (index == 2) {
        this.number_login = true;
        this.phonePassword_login = false;
        this.phoneCode_login = false
      } else if (index == 1) {
        this.number_login = false;
        this.phonePassword_login = false;
        this.phoneCode_login = true;
        this.imgCdoe();
        this.loginForm.mobile = '';
        this.loginForm.sign = '';
        this.loginForm.code = '';

      }
    },
    cut () {//切换图片验证码
      this.imgCdoe();
    },
    imgCdoe () {
      this.$store.dispatch('getImgCodeLog').then((res)=>{
          if (res.data.code == 'OK') {
              this.kid = res.data.data.kid;
              this.sign = res.data.data.src;
          } else {
            this.$message({
               showClose: true,
               message: res.data.message,
               type: 'error'
             });
          }
      })
    },
    getCdoe () {
        if (this.loginForm.sign.length == 4) {
              var data =  {
                mobile : Base64.encode(this.loginForm.mobile),
                kid : this.kid,
                sign : this.loginForm.sign,
                client : '1'
              }
              getNoteCode(data).then(res=>{
                if (res.data.code == 'OK') {
                  this.loginForm.ticket = res.data.data;
                  const TIME_COUNT = 60;
                    if (!this.timer) {
                      this.count = TIME_COUNT;
                      this.show = false;
                      this.timer = setInterval(() => {
                      if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--;
                       } else {
                        this.show = true;
                        clearInterval(this.timer);
                        this.timer = null;
                       }
                      }, 1000)
                   }
                } else {
                  // this.$message.error(res.code.message)
                  console.log(res);
                }
                console.log(res);
              })
        } else {
          this.$message.error('请输入图片验证码')
        }

    },
    // showPwd() {
    //   if (this.passwordType === 'password') {
    //     this.passwordType = ''
    //   } else {
    //     this.passwordType = 'password'
    //   }
    // },
    handleLogin () {
      if (this.number_login == true) {
          this.loginForm['loginType'] = 'ACCOUNT'
          this.$refs.loginForm.validate(valid => {
            if (valid) {
              this.loading = true;
              this.$store.dispatch('LoginByUsername', this.loginForm).then((res) => {
                this.loading = false
                if (res.data.code == 'OK') {
                  this.$message({
                     showClose: true,
                     message: '登录成功',
                     type: 'success'
                   });
                } else {
                  this.$message({
                     showClose: true,
                     message: res.data.message,
                     type: 'error'
                   });
                     this.loading = false
                }
                this.$router.push({
                  name :'Dashboard'
                })
              }).catch((data) => {
                this.loading = false
              })
            } else {
              console.log('error submit!!')
              return false
            }
          })
          // loginByUsername(JSON.stringify(this.data)).then((data)=>{
          //     console.log(data)
          // })
      } else if (this.phoneCode_login == true) {
          this.loginForm['loginType'] = 'KAPTCHA'
            this.$store.dispatch('PhoneCodeLogin',this.loginForm).then((res)=>{
               this.loading = true;
               if (res.data.code == 'OK') {
                 this.$message({
                    showClose: true,
                    message: '登录成功',
                    type: 'success'
                  });
                  this.$router.push('/dashboard')
                     this.loading = false;
               } else {
                 this.$message({
                    showClose: true,
                    message: res.data.message,
                    type: 'error'
                  });
               }
          })
       } else {
         this.loginForm['loginType'] = 'KAPTCHA'
           this.$store.dispatch('passwordLogin',this.loginForm).then((res)=>{
              this.loading = true;
              if (res.data.code == 'OK') {
                this.$message({
                   showClose: true,
                   message: '登录成功',
                   type: 'success'
                 });
                 this.$router.push('/dashboard')
                    this.loading = false;
              } else {
                this.$message({
                   showClose: true,
                   message: res.data.message,
                   type: 'error'
                 });
                this.loading = false;
              }
         })
       }
    },
    afterQRScan() {
      // const hash = window.location.hash.slice(1)
      // const hashObj = getQueryObject(hash)
      // const originUrl = window.location.origin
      // history.replaceState({}, '', originUrl)
      // const codeMap = {
      //   wechat: 'code',
      //   tencent: 'code'
      // }
      // const codeName = hashObj[codeMap[this.auth_type]]
      // if (!codeName) {
      //   alert('第三方登录失败')
      // } else {
      //   this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
      //     this.$router.push({ path: '/' })
      //   })
      // }
    }
  }
}
</script>

<style scoped>
#login_wap {
  width: 100%;
  height: 100%;
}
.login-bg {
    width: 100%;
    height: 100%;
    background: url('../../assets/imgs/login-bg.jpg') no-repeat;
    background-size: 100%;
    position: relative;
  }
.login-box {
  width: 300px;
  position: absolute;
  right: 160px;
  top: 50%;
  transform: translateY(-60%);
  width: 300px;
  background: #fff;
  box-sizing: border-box;
  border-radius: 5px;
}
.login-box h2 {
  margin: 10px 0;
  padding: 10px 0;
  box-sizing: border-box;
  border-bottom: 1px solid rgba(0,0,0,0.5);
  text-indent: 20px;
}
.login-content {
  padding:0 20px;
}
.demo-ruleForm {
  margin:30px 0px;
}
.submit_btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
.forget_password {
  text-align: center;
  color: #409EFF;
  cursor: pointer;
}
.forget_password:hover {
  text-decoration: underline;
}
.password_box {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.code_box {
  position: relative;
  z-index: 11;
}
.code {
  position: absolute;
  top:0;
  right:0px;
  z-index: 999;
}
.el-input__inner {
  width: 144px;
}
.codeImg {
  width:149px;

}
.img_box {
  display: flex;
}
</style>
